package org.openjava.utils;
import java.lang.reflect.Array;
import java.util.regex.Pattern;


  
public class ArrayUtils {
	public void testNewInstanceByLength(){
		Object obj = Array.newInstance(String[].class, 20);
		Object[] objs = (Object[]) obj.getClass().cast(obj);
		System.out.println(objs.getClass());
	}
	
	public  void testNewInstanceByDimension() {
		Object obj = Array.newInstance(String.class,1,2,3,4);
		Object[] objs = (Object[]) obj.getClass().cast(obj);
		System.out.println(objs.getClass());
	}
	
	
	public  static int countArrayDeep(Object object){
		String className = object.getClass().getName();
		int count = 0;
		for(int i = 0, j = className.length();i < j;i ++){
			if(className.charAt(i) == '['){
				count ++;
				continue;
			}
			break;
		}
		return count;
	}
	

	public static boolean isPrimitiveArray(Object obj){
		return Pattern.matches("^\\[*[CBSIJFD]{1}$",obj.getClass().getName());
	}
	
	public static  Object getElByIndex(Object obj,int index){
		Object result = null;
		if(obj.getClass().getComponentType().isArray()){
			Object[] objs = (Object[]) obj.getClass().cast(obj);
			result = objs[index];
		}else{
			if(isPrimitiveArray(obj)){
				String className = obj.getClass().getName();
				String key = className.substring(className.length() -1);
				int type = "CBSIJFD".indexOf(key);
				switch(type){
				case 0:result = Array.getChar(obj, index);
					break;
				case 1:result = Array.getByte(obj, index);
					break;
				case 2:result = Array.getShort(obj, index);
					break;
				case 3:result = Array.getInt(obj, index);
					break;
				case 4:result = Array.getLong(obj, index);
					break;
				case 5:result = Array.getFloat(obj, index);
					break;
				case 6:result = Array.getDouble(obj, index);
					break;
				}
			}else{
				Object[] objs = (Object[]) obj;
				result = objs[index];
			}
		}
		return result;
	}
}
